import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22652
 * Date: 2024-05-28
 * Time: 0:11
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        resp.setContentType("text/html; charset=utf-8");
        HttpSession session = req.getSession(false);
        // 1. 判定当前用户是否已经登陆
        if (session == null) {
// 用户没有登陆, 重定向到 login.html
            resp.sendRedirect("register.html");
            return;
        }
// 设置 Session
        String userName = (String) session.getAttribute("username");
        String countString = (String) session.getAttribute("loginCount");
        String passWord =(String) session.getAttribute("password");

// 1. 获取到用户提交的用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
// 2. 判定用户名密码是否正确
        if (!username.equals(userName) || !password.equals(passWord)) {
// 登陆失败
            resp.getWriter().write("登陆失败");
            return;
        }
// 登陆成功
        int loginCount = Integer.parseInt(countString);
        loginCount += 1;
        session.setAttribute("loginCount", loginCount + "");
        System.out.println("登陆成功");
        resp.sendRedirect("index");
    }
}